package com.geek688.auxiliarytool.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.sl.extractor.SlideShowExtractor;
import org.apache.poi.sl.usermodel.SlideShowFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import com.itextpdf.text.pdf.PdfReader;
//import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
//import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
//import com.itextpdf.text.pdf.parser.TextExtractionStrategy;


public class ReadDocumentUtil {

	private static Logger log = LoggerFactory.getLogger(ReadDocumentUtil.class);

	/**
     * 判断文件是否存在
     *
     * @Title: isExists
     * @param @param filePath
     * @param @return
     * @return boolean 返回类型
     * @throws
     */
    public static boolean isExists(String filePath) {
        File file = new File(filePath);
        if (!file.exists() && !file.isDirectory()) {
            return false;
        } else {
            return true;
        }
    }
    
    /**
     * @Title: getTextFromPdf
     * @Description: 获取指定位置pdf的文件内容
     * @param @param filePath
     * @param @return
     * @param @throws IOException
     * @return String 返回类型
     * @throws
     */
//    public static String getTextFromPdf(String filePath) {
//        PdfReader reader;
//		try {
//			reader = new PdfReader(filePath);
//			PdfReaderContentParser parser = new PdfReaderContentParser(reader);
//	        StringBuffer buff = new StringBuffer();
//	        TextExtractionStrategy strategy;
//	        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
//	            strategy = parser.processContent(i,
//	                    new SimpleTextExtractionStrategy());
//	            buff.append(strategy.getResultantText());
//	        }
//	        return buff.toString();
//		} catch (Exception e) {
//			log.error("读取pdf文档失败，请检查文档格式！",e);
//		}
//		return "";
//    }
    
    /**
     * @Title: getTextFromPPT(兼容ppt、pptx)
     * @Description: 获取指定位置ppt的文件内容
     * @param @param filePath
     * @param @return
     * @param @throws IOException
     * @return String 返回类型
     * @throws
     */
    @SuppressWarnings({ "unchecked", "rawtypes", "static-access", "resource" })
	public static String getTextFromPPT(String filePath) {
    	SlideShowFactory slideShowFactory = new SlideShowFactory();
    	FileInputStream fis = null;
		try {
			fis = new FileInputStream(filePath);
			SlideShowExtractor extractor = new SlideShowExtractor(slideShowFactory.create(fis));
			return extractor.getText();
		} catch (FileNotFoundException e) {
			log.error("加载文档失败，请检查文档路径！",e);
		} catch (IOException e) {
			log.error("读取文档失败，请检查文档格式!",e);
		} finally {
			ReadDocumentUtil.close(fis);
		}
		return "";
    }
    
    public static List<Cell> getExcelCells(String filePath) {
		List<Row> rows = getExcelRows(filePath);
		List<Cell> cells = new ArrayList<>();
		int lastRowNum = rows.size();
		for (int index = 0; index < lastRowNum; index++) {
			Row row = rows.get(index);// 获得一个行
			if (row == null) {
				continue;
			}
			short lastCellNum = row.getLastCellNum();
			for (int cellNumOfRow = 0; cellNumOfRow <= lastCellNum; cellNumOfRow++) {
				Cell cell = row.getCell(cellNumOfRow);// 获得列值
				if (cell == null) {
					continue;
				}
				cells.add(cell);
			}
		}
		return cells;
	}
    public static List<Row> getExcelRows(String filePath) {
    	List<Sheet> list = getExcelSheets(filePath);
    	List<Row> rows = new ArrayList<>();
		int sheets = list.size();
		for (int numSheets = 0; numSheets < sheets; numSheets++) {
			Sheet sheet = list.get(numSheets);// 获得一个sheet
			if (sheet == null) {
				continue;
			}
			int lastRowNum = sheet.getLastRowNum();
			for (int rowNumOfSheet = 0; rowNumOfSheet <= lastRowNum; rowNumOfSheet++) {
				Row row = sheet.getRow(rowNumOfSheet);// 获得一个行
				if (row == null) {
					continue;
				}
				rows.add(row);
			}
		}
		return rows;
	}
    public static List<Sheet> getExcelSheets(String filePath) {
    	// 创建对Excel工作簿文件的引用
		Workbook wb = readExcel(filePath);
		List<Sheet> list = new ArrayList<>();
		// 创建对工作表的引用。
		int sheets = wb.getNumberOfSheets();
		for (int index = 0; index < sheets; index++) {
			Sheet sheet = wb.getSheetAt(index);// 获得一个sheet
			if (sheet == null) {
				continue;
			}
			list.add(sheet);
		}
		return list;
	}
    /**
     * 读取excel内容(兼容 xls、xlsx)
     *
     * @Title: getTextFromExcel
     * @param @param filePath
     * @param @return
     * @return String 返回类型
     * @throws
     */
    public static String getTextFromExcel(String filePath) {
        StringBuffer buff = new StringBuffer();
        // 创建对Excel工作簿文件的引用
		Workbook wb = readExcel(filePath);
		// 创建对工作表的引用。
		for (int numSheets = 0; numSheets < wb.getNumberOfSheets(); numSheets++) {
		    if (null != wb.getSheetAt(numSheets)) {
		    	Sheet aSheet = wb.getSheetAt(numSheets);// 获得一个sheet
		        for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet
		                .getLastRowNum(); rowNumOfSheet++) {
		            if (null != aSheet.getRow(rowNumOfSheet)) {
		            	Row aRow = aSheet.getRow(rowNumOfSheet); // 获得一个行
		                for (int cellNumOfRow = 0; cellNumOfRow <= aRow
		                        .getLastCellNum(); cellNumOfRow++) {
		                    if (null != aRow.getCell(cellNumOfRow)) {
		                        Cell aCell = aRow.getCell(cellNumOfRow);// 获得列值
		                        switch (aCell.getCellType()) {
		                        case FORMULA:
		                            break;
		                        case NUMERIC:
		                            buff.append(aCell.getNumericCellValue()).append('\t');
		                            break;
		                        case STRING:
		                            buff.append(aCell.getStringCellValue()).append('\t');
		                            break;
								case BLANK:
									buff.append(aCell.getStringCellValue()).append('\t');
									break;
								case BOOLEAN:
									buff.append(aCell.getBooleanCellValue()).append('\t');
									break;
								case ERROR:
									break;
								case _NONE:
									buff.append(aCell.getStringCellValue()).append('\t');
									break;
								default:
									buff.append(aCell.getStringCellValue()).append('\t');
									break;
		                        }
		                    }
		                }
		                buff.append('\n');
		            }
		        }
		    }
		}
        return buff.toString();
    }
    
	public static Workbook readExcel(String fileName){
		Workbook wb = null;
        if(fileName==null){
            return null;
        }
        String extString = fileName.substring(fileName.lastIndexOf("."));
        FileInputStream is = null;
        try {
            is = new FileInputStream(fileName);
            if(".xls".equals(extString)){
                return wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(extString)){
                return wb = new XSSFWorkbook(is);
            }
        } catch (FileNotFoundException e) {
            log.error("加载文档失败，请检查文档路径！",e);
        } catch (IOException e) {
        	log.error("读取文档失败，请检查文档格式!",e);
        } finally {
			ReadDocumentUtil.close(is);
		}
        return wb;
	}
    
	/**
     * 获取word文档内容(兼容doc、docx)
     *
     * @Title: getTextFromWord
     * @param @param filePath
     * @param @return
     * @return String 返回类型
     * @throws
     */
    public static String getTextFromWord(String filePath) {
    	String result = "";
    	try {
			result = getDocFileText(filePath);
		} catch (IllegalArgumentException e) {
			result = getDocxFileText(filePath);
		} catch (Exception e) {
			log.error("读取word文档失败，请检查文档格式！",e);
		} 
    	return result;
	}
    
    @SuppressWarnings("resource")
	public static String getDocFileText(String filePath) throws Exception {
        File file = new File(filePath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            HWPFDocument doc = new HWPFDocument(fis);
            return doc.getDocumentText();
        } catch (Exception e) {
           throw e;
        } finally {
        	ReadDocumentUtil.close(fis);
		}
    }
    
    @SuppressWarnings({ "resource", "finally" })
	public static String getDocxFileText(String filePath) {
        File file = new File(filePath);
        FileInputStream fis = null;
        String result = "";
        try {
            fis = new FileInputStream(file);
            XWPFDocument xdoc = new XWPFDocument(fis);
            XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(xdoc);
            result = xwpfWordExtractor.getText();
        } catch (Exception e) {
        	log.error("",e);
        } finally {
        	ReadDocumentUtil.close(fis);
        	return result;
		}
    }
    
    private static void close(FileInputStream fis) {
    	if (fis != null) {
			try {
				fis.close();
				fis = null;
			} catch (IOException e) {
				log.error("流关闭异常！",e);
			}
		}
    }
}
